package Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import Util.JdbcUtil;
import Entity.Admin;

public class AdminDao {
    //	增
    public void add(String username, String password) {
        try {
            Connection conn = JdbcUtil.getConnection();
            String sql = "insert into admin(username,password,code) values('" + username + "','" + password + "','2');";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.executeUpdate();
            JdbcUtil.close(pstmt, conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //	删
    public void delete(int id) {
        try {
            Connection conn = JdbcUtil.getConnection();
            String sql = "delete from admin where id = " + id + ";";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.executeUpdate();
            JdbcUtil.close(pstmt, conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //	改
    public void update(int id, String password) {
        try {
            Connection conn = JdbcUtil.getConnection();
            String sql = "update admin set password='" + password + "' where id=" + id + ";";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.executeUpdate();
            JdbcUtil.close(pstmt, conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //	查
    public List<Admin> select() {
        List<Admin> list = new ArrayList<Admin>();
        try {
            Connection conn = JdbcUtil.getConnection();
            String sql = "select * from admin;";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Admin admins = new Admin();
                admins.setId(rs.getInt(1));
                admins.setUsername(rs.getString(2));
                admins.setPassword(rs.getString(3));
                admins.setCode(rs.getInt(4));
                list.add(admins);
            }
            JdbcUtil.close(pstmt, conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }
}
